package com.llkj.qingnianguoxue.mine;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.llkj.qingnianguoxue.MainActivity;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.ResponseBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.AgreementActivity;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.util.AppManager;
import com.llkj.qingnianguoxue.util.DownloadService;
import com.llkj.qingnianguoxue.util.FileOperation;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.Utils;
import com.sevenheaven.iosswitch.ShSwitchView;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import rx.functions.Action1;

/**
 * 系统设置
 */
public class SystemSettingActivity extends BaseActivity {
    private static final int REQUEST_CODE = 7788;
    private RelativeLayout rlModifyPwd, rlClearCache, rlAboutUs, rlUpdateVersion, rlFeedback;//修改密码，清除缓存，关于我们，版本更新，意见反馈
    private TextView tvVersion, tvCache;//版本
    private ShSwitchView switchPush, switchWifiPlay;//消息推送，非WIFI开关
    private ImageView ivVersionGo;
    private String apkPath;
    private int dialogType;//1退出，2更新
    private boolean isPermissions;
    private String mServiceAppVersion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_system_setting);
        setTitle("设置", true, TITLE_TYPE_IMG, R.drawable.icon_back, false, TITLE_TYPE_TEXT, null);
        ButterKnife.bind(this);
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        isPermissions = aBoolean;
                    }
                });
        initView();
        initListener();

        tvVersion.setText("v" + Utils.getCurrentVersion(this).versionName);

        HttpMethod.userVersion(this, this);
    }

    private void initView() {
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
        switchPush = (ShSwitchView) findViewById(R.id.switch_push);//消息推送，非WIFI开关
        switchWifiPlay = (ShSwitchView) findViewById(R.id.switch_wifi);
        rlModifyPwd = (RelativeLayout) findViewById(R.id.rl_update_pwd);//修改密码
        rlClearCache = (RelativeLayout) findViewById(R.id.rl_clear_cache);//清除缓存
        rlAboutUs = (RelativeLayout) findViewById(R.id.rl_about_us);//关于我们
        rlUpdateVersion = (RelativeLayout) findViewById(R.id.rl_app_update);//版本更新
        tvCache = (TextView) findViewById(R.id.tv_cache_size);//
        tvVersion = (TextView) findViewById(R.id.tv_version_name);//版本号
        rlFeedback = (RelativeLayout) findViewById(R.id.rl_idea_back);//意见反馈
        ivVersionGo = findViewById(R.id.iv_version_gone);

        String isPush = MyApplication.getInstance().sputil.getString(ConstantUserInfo.IS_PUSH);
        if ("1".equals(isPush)) {
            switchPush.setOn(true);
        } else {
            switchPush.setOn(false);
        }

        String isNotification = MyApplication.getInstance().sputil.getString(ConstantUserInfo.IS_WIFI_NOTIFICATION);
        if ("1".equals(isNotification)) {
            switchWifiPlay.setOn(true);
        } else {
            switchWifiPlay.setOn(false);
        }
    }

    private void initListener() {
        switchPush.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                if (isOn) {
                    setPush("1");
                } else {
                    setPush("2");
                }
            }
        });
        switchWifiPlay.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                if (isOn) {
                    MyApplication.getInstance().sputil.put(ConstantUserInfo.IS_WIFI_NOTIFICATION, "1");
                } else {
                    MyApplication.getInstance().sputil.put(ConstantUserInfo.IS_WIFI_NOTIFICATION, "2");
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @OnClick({R.id.rl_update_pwd, R.id.rl_clear_cache, R.id.rl_about_us, R.id.rl_app_update, R.id.rl_idea_back, R.id.tv_login_out})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_update_pwd://修改密码
                startActivityForResult(ModifyPwdActivity.class, new Bundle(), REQUEST_CODE);
                break;
            case R.id.rl_clear_cache:////清除缓存
                if (!isPermissions) {
                    ToastUtil.makeLongText(this, getString(R.string.permission_write));
                    return;
                }
                dialogType = 1;
                dialogConfirm("确定清除本地缓存", "", "取消", "确定").show();
                break;
            case R.id.rl_about_us://关于我们
                Bundle bundle = new Bundle();
                bundle.putInt(AgreementActivity.FROM_CLASS, 2);
                startActivity(AgreementActivity.class, bundle);
                break;
            case R.id.rl_app_update://版本更新
                if (!StringUtils.isEmpty(apkPath)) {
                    if (!isPermissions) {
                        ToastUtil.makeLongText(this, getString(R.string.permission_write));
                        return;
                    }
                    if(Utils.getCurrentVersion(this).versionName.compareTo(mServiceAppVersion)>=0){
                        return;
                    }
                    dialogType = 2;
                    dialogConfirm("系统将升级到v" + mServiceAppVersion + "版本", "是否进行更新？", "暂不更新", "立即更新").show();
                } else {
//                    ToastUtil.makeLongText(this, getString(R.string.check_version));
                }
                break;
            case R.id.rl_idea_back://帮助和反馈
                startActivity(HelpActivity.class);
                break;
            case R.id.tv_login_out://退出登录
                dialogType = 3;
                dialogConfirm("是否退出登录", "", "取消", "确定").show();
                break;
        }
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        if (dialogType == 2) {//更新版本
            if (!StringUtils.isEmpty(apkPath)) {
                Intent intent = new Intent(this, DownloadService.class);
                intent.putExtra("url", apkPath);
                startService(intent);
            } else {
                ToastUtil.makeLongText(this, "当前是最新版本");
            }

        } else if (dialogType == 1) {//清除缓存
            loadWaitDialog();

            new Thread() {
                @Override
                public void run() {
                    Message msg = new Message();
                    try {
                        String external = Environment
                                .getExternalStorageDirectory().getPath() + "/Android/data/" + getPackageName();
                        String cacheDir = getCacheDir().getPath() + getPackageName();
                        FileOperation.deleteFiles(new File(external));
                        FileOperation.deleteFiles(new File(cacheDir));

                        clearCacheDiskSelf();

                        msg.what = 1;
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                        msg.what = -1;
                    }
                    handler.sendMessage(msg);
                }
            }.start();
        }else if(dialogType == 3){//退出登录
            MyApplication.getInstance().sputil.put(ConstantUserInfo.ISLOGIN, false);
            MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_ID, "");

//            AppManager.getInstance().finishActivity(MainActivity.class);

            try {
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                wechat.removeAccount(true);
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                qq.removeAccount(true);
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                sina.removeAccount(true);
            }catch (Exception e){}

            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("login_out", "1");
            startActivity(intent);
//            finish();
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dismissWaitDialog();
            if (msg.what == 1) {
                ToastUtil.makeLongText(SystemSettingActivity.this, "缓存清除完成！");
                tvCache.setText("0M");
            } else {
                ToastUtil.makeLongText(SystemSettingActivity.this, "缓存清除失败！");
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        String external = Environment
                .getExternalStorageDirectory().getPath() + "/Android/data/" + getPackageName() + "/img/";
        String cacheDir = getCacheDir().getPath() + getPackageName() + "/img/";

        float size = 0;
        File file = new File(external);
        size += file.getTotalSpace();
        file = new File(cacheDir);
        size += file.getTotalSpace();

        external = Environment
                .getExternalStorageDirectory().getPath() + "/Android/data/" + getPackageName() + "/book/";
        cacheDir = getCacheDir().getPath() + getPackageName() + "/book/";

        file = new File(external);
        size += file.getTotalSpace();
        file = new File(cacheDir);
        size += file.getTotalSpace();
        size += getCacheSize();

        tvCache.setText(String.format("%.2f", size / (1024 * 1024 * 1024)) + "M");
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_USER_VERSION) {//版本更新
            ResponseBean responseBean = GsonUtil.GsonToBean(data, ResponseBean.class);
            if (responseBean != null) {
                String versionName = Utils.getCurrentVersion(this).versionName;
                    mServiceAppVersion = responseBean.getTitle();
                    if(versionName.compareTo(mServiceAppVersion)>=0){
                        tvVersion.setText("已是最新版本");
                        ivVersionGo.setVisibility(View.GONE);
                    }else{
                        tvVersion.setText("立即更新");
                        apkPath = responseBean.getApk();
                    }
            }
        } else if (method == HttpMethod.HTTP_USER_IS_PUSH) {//是否推送
            String isPush = MyApplication.getInstance().sputil.getString(ConstantUserInfo.IS_PUSH);
            if ("1".equals(isPush)) {
                MyApplication.getInstance().sputil.put(ConstantUserInfo.IS_PUSH, "2");
            } else {
                MyApplication.getInstance().sputil.put(ConstantUserInfo.IS_PUSH, "1");
            }
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        if (!StringUtils.isEmpty(message)) {
            ToastUtil.makeLongText(this, message);
        }
    }

    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    public long getCacheSize() {
        try {
            return getFolderSize(new File(getCacheDir() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception
     */
    private long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * Glide清除缓存
     *
     * @return
     */
    public boolean clearCacheDiskSelf() {
        try {
            Glide.get(MyApplication.getInstance()).clearDiskCache();
            Glide.get(MyApplication.getInstance()).clearMemory();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 是否tuis
     *
     * @param isPush 1是，2否
     */
    private void setPush(String isPush) {
//        loadWaitDialog();
        HttpMethod.isPush(this, this, isPush);
    }
}
